package dao

import (
	"fmt"
	"gitee.com/git_public/vfaith/builtin/vault"
	"gitee.com/git_public/vfaith/fount/frame"
	"gitee.com/git_public/vfaith/fount/persist"
	"gitee.com/git_public/vfaith/toolkit/generate/model/po"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"strconv"
)

// region 结构体定义&构造

func init() {
	frame.DaoRegistry[*ColumnsDAO]()
}

// ColumnsDAO 结构体封装了对用户表的操作
type ColumnsDAO struct {
	*persist.OexSqlxAlpha
}

func (dao *ColumnsDAO) DaoInitialize() {
	dao.OexSqlxAlpha = persist.GetOexDefault()
}

// endregion

func (dao *ColumnsDAO) GetColumns(tableName string) ([]po.Column, error) {
	query := `
		SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_TYPE, COLUMN_KEY, COLUMN_COMMENT
		FROM INFORMATION_SCHEMA.COLUMNS 
		WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?
		order by ORDINAL_POSITION
	`

	log.Printf("SQL【%s】", query)
	log.Printf("SQL【%s】", tableName)

	rows, err := dao.Query(query, tableName)
	if err != nil {
		return nil, fmt.Errorf(fmt.Sprintf("获取columns失败: %v", err))
	}
	defer rows.Close()

	var columns []po.Column
	for rows.Next() {
		var column po.Column
		var isNullable string
		if err = rows.Scan(&column.Name, &column.Type, &isNullable, &column.ColumnType, &column.ColumnKey, &column.ColumnComment); err != nil {
			return nil, fmt.Errorf(fmt.Sprintf("获取columns失败: %v", err))
		}
		column.Nullable = isNullable == "YES"
		columns = append(columns, column)
	}
	if err = rows.Err(); err != nil {
		return nil, fmt.Errorf(fmt.Sprintf("获取columns失败: %v", err))
	}

	log.Printf("查询获得表信息【%s】条", strconv.Itoa(len(columns)))
	return columns, nil
}

func (dao *ColumnsDAO) GetTableMap(sql string) (*vault.TableMap, error) {
	tableMap, err := dao.ScanToMap(sql)
	if err != nil {
		return tableMap, fmt.Errorf(fmt.Sprintf("gen_dao：数据源查询失败: %v", err))
	}
	return tableMap, nil
}
